package org.agile4j.patterns;

import java.util.Arrays;
@SuppressWarnings("rawtypes")
class BineryTree {
	private class Node {
		private Node left;
		private Node right;
		private Comparable data;
		public Node(Comparable data) {
			this.data = data;
		}

		/**
		 * addNode 方法
		 * 1) 根据compareTo方法 设定左子树,右子树
		 * 2) this 是根节点 第一个数据设定为根节点与其比较
		 * 3) 递归操作中不同的自调时 进去几次也会出来几次
		 * @param newNode
		 */
		@SuppressWarnings("unchecked")
		public void addNode(Node newNode) {
			if (this.data.compareTo(newNode.data) > 0) {
				if (this.left == null) {
					this.left = newNode;
				} else {
					this.left.addNode(newNode);
				}
			} else {
				if (this.right == null) {
					this.right = newNode;
				} else {
					this.right.addNode(newNode);
				}
			}
		}

		public void toArrayNode() {
			if (this.left != null) {
				this.left.toArrayNode();
			}
			BineryTree.this.retData[BineryTree.this.foot++] = this.data;
			if (this.right != null) {
				this.right.toArrayNode();
			}
		}

	}

	// 根节点
	private Node root;
	// 记录节点数量
	private int count;
	private int foot;
	private Object[] retData;

	public void add(Comparable data) {
		Node newNode = new Node(data);
		if (root == null) {
			root = newNode;
		} else {
			root.addNode(newNode);
		}
		count++;
	}

	public Object[] toArray() {
		retData = new Object[count] ;
		if (root != null) {
			root.toArrayNode();
		}
		return retData;
	}
}

public class BineryTreeDemo {
	public static void main(String[] args) {
		BineryTree bt = new BineryTree() ;
		bt.add("F");
		bt.add("A");
		bt.add("H");
		bt.add("4");
		bt.add("N");
		bt.add("K");
		bt.add("V");
		System.out.println(Arrays.toString(bt.toArray()));
	}
}
